<template>
  <div class="document-player">
    <header class="player-header">
      <div class="header-content">
        <h1 class="document-title">{{ title || '文档查看器' }}</h1>
        <div class="player-controls">
          <button @click="downloadDocument" class="btn btn-secondary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
              <polyline points="7,10 12,15 17,10"/>
              <line x1="12" y1="15" x2="12" y2="3"/>
            </svg>
            下载
          </button>
          <button @click="closePlayer" class="btn btn-primary">关闭</button>
        </div>
      </div>
    </header>

    <main class="player-content">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载文档...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <h3>文档加载失败</h3>
        <p>{{ error }}</p>
        <button @click="retryLoad" class="btn btn-primary">重试</button>
      </div>

      <div v-else class="document-container">
        <!-- PDF文档 - 使用浏览器内置查看器 -->
        <iframe 
          v-if="isPDF"
          :src="documentUrl" 
          class="document-iframe"
          title="PDF文档查看器"
          @load="onIframeLoad"
          @error="onIframeError"
        ></iframe>

        <!-- Office文档 - 生产环境使用Office Online，本地环境提供下载选项 -->
        <iframe
          v-if="isOfficeDocument && canUseOfficeOnline"
          :src="officeOnlineUrl"
          class="document-iframe"
          title="Office文档查看器"
          @load="onIframeLoad"
          @error="onOfficeOnlineError"
        ></iframe>

        <!-- Office文档 - 本地环境或Office Online失败时的备选方案 -->
        <div v-else-if="isOfficeDocument" class="office-document-viewer">
          <div class="office-info">
            <div class="office-icon">📄</div>
            <h3>{{ getFileTypeName() }} 文档</h3>
            <p class="document-name">{{ title }}</p>
            <p class="info-text" v-if="!isProduction">本地开发环境下，Office文档需要下载后使用相应软件查看</p>
            <p class="info-text" v-else>Office在线查看器暂时不可用，请下载文档后查看</p>
            
            <div class="supported-apps">
              <h4>支持的应用：</h4>
              <ul>
                <li v-if="isWordDocument">Microsoft Word、WPS Writer、LibreOffice Writer</li>
                <li v-if="isExcelDocument">Microsoft Excel、WPS表格、LibreOffice Calc</li>
                <li v-if="isPowerPointDocument">Microsoft PowerPoint、WPS演示、LibreOffice Impress</li>
              </ul>
            </div>

            <div class="download-actions">
              <button @click="downloadDocument" class="btn btn-primary btn-large">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                  <polyline points="7,10 12,15 17,10"/>
                  <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                立即下载
              </button>
              <button @click="openInNewTab" class="btn btn-secondary">
                在新窗口打开
              </button>
            </div>
          </div>
        </div>

        <!-- 其他文档类型 - 尝试直接显示 -->
        <div v-else class="generic-document-viewer">
          <iframe 
            :src="documentUrl" 
            class="document-iframe"
            title="文档查看器"
            @load="onIframeLoad"
            @error="onIframeError"
          ></iframe>
          
          <!-- 加载失败时显示备选选项 -->
          <div v-if="showFallback" class="fallback-options">
            <div class="fallback-icon">📄</div>
            <h3>无法预览此文档</h3>
            <p>此文档格式不支持在线预览，请下载后查看</p>
            
            <div class="fallback-actions">
              <button @click="downloadDocument" class="btn btn-primary">
                下载文档
              </button>
              <button @click="openInNewTab" class="btn btn-secondary">
                新窗口打开
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

// 状态管理
const loading = ref(true)
const error = ref<string | null>(null)
const showFallback = ref(false)

// 从URL参数获取文档信息
const documentUrl = computed(() => {
  const url = route.query.url as string
  return url ? decodeURIComponent(url) : ''
})

const title = computed(() => {
  const titleParam = route.query.title as string
  return titleParam ? decodeURIComponent(titleParam) : '文档查看器'
})

// 判断是否为生产环境
const isProduction = computed(() => {
  const url = documentUrl.value.toLowerCase()
  return !url.includes('localhost') && !url.includes('127.0.0.1') && !url.includes('192.168.')
})

// 判断文档类型
const isPDF = computed(() => {
  return documentUrl.value.toLowerCase().includes('.pdf')
})

const isOfficeDocument = computed(() => {
  const url = documentUrl.value.toLowerCase()
  return url.includes('.doc') || url.includes('.docx') || 
         url.includes('.ppt') || url.includes('.pptx') || 
         url.includes('.xls') || url.includes('.xlsx')
})

// 是否可以使用Office Online查看器
const canUseOfficeOnline = computed(() => {
  return isOfficeDocument.value && isProduction.value
})

const isWordDocument = computed(() => {
  const url = documentUrl.value.toLowerCase()
  return url.includes('.doc') || url.includes('.docx')
})

const isExcelDocument = computed(() => {
  const url = documentUrl.value.toLowerCase()
  return url.includes('.xls') || url.includes('.xlsx')
})

const isPowerPointDocument = computed(() => {
  const url = documentUrl.value.toLowerCase()
  return url.includes('.ppt') || url.includes('.pptx')
})

// Office Online查看器URL
const officeOnlineUrl = computed(() => {
  if (!canUseOfficeOnline.value) return ''
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(documentUrl.value)}`
})

// 获取文件类型名称
const getFileTypeName = () => {
  const url = documentUrl.value.toLowerCase()
  if (url.includes('.pdf')) return 'PDF'
  if (url.includes('.doc') || url.includes('.docx')) return 'Word'
  if (url.includes('.ppt') || url.includes('.pptx')) return 'PowerPoint'
  if (url.includes('.xls') || url.includes('.xlsx')) return 'Excel'
  if (url.includes('.txt')) return '文本'
  return '文档'
}

// 加载文档
const loadDocument = async () => {
  loading.value = true
  error.value = null
  showFallback.value = false

  try {
    if (!documentUrl.value) {
      throw new Error('文档URL不能为空')
    }

    console.log('正在加载文档:', documentUrl.value)

    // 检查文档是否可访问
    const response = await fetch(documentUrl.value, { method: 'HEAD' })
    if (!response.ok) {
      throw new Error(`文档无法访问 (HTTP ${response.status})`)
    }

    console.log('文档检查成功，文件存在')
    loading.value = false
  } catch (err: any) {
    console.error('文档检查失败:', err)
    error.value = err.message || '文档加载失败'
    loading.value = false
  }
}

// 重试加载
const retryLoad = () => {
  loadDocument()
}

// iframe加载成功
const onIframeLoad = () => {
  console.log('iframe加载成功')
  showFallback.value = false
}

// iframe加载失败
const onIframeError = () => {
  console.log('iframe加载失败，显示备选选项')
  setTimeout(() => {
    showFallback.value = true
  }, 2000) // 2秒后显示备选选项
}

// Office Online加载失败的处理
const onOfficeOnlineError = () => {
  console.log('Office Online查看器加载失败，切换到下载模式')
  // 强制切换到下载模式
  showFallback.value = true
}

// 下载文档
const downloadDocument = () => {
  if (documentUrl.value) {
    console.log('开始下载文档:', documentUrl.value)
    const link = document.createElement('a')
    link.href = documentUrl.value
    link.download = title.value || 'document'
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 在新窗口打开
const openInNewTab = () => {
  if (documentUrl.value) {
    window.open(documentUrl.value, '_blank')
  }
}

// 关闭播放器
const closePlayer = () => {
  window.close()
}

// 页面加载时初始化
onMounted(() => {
  loadDocument()
})
</script>

<style scoped>
.document-player {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.player-header {
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  padding: 1rem 2rem;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.document-title {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
  font-weight: 600;
}

.player-controls {
  display: flex;
  gap: 1rem;
}

.player-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  overflow: hidden;
}

.loading-container, .error-container {
  text-align: center;
  padding: 3rem;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.document-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.document-iframe {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.office-document-viewer {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.office-info {
  background: white;
  padding: 3rem;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 500px;
}

.office-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.office-info h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.5rem;
  color: #333;
}

.document-name {
  font-size: 1.1rem;
  color: #666;
  margin: 0 0 1.5rem 0;
  font-weight: 500;
}

.info-text {
  color: #888;
  margin: 0 0 2rem 0;
  line-height: 1.5;
}

.supported-apps {
  text-align: left;
  margin: 2rem 0;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.supported-apps h4 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1rem;
}

.supported-apps ul {
  margin: 0;
  padding-left: 1.5rem;
}

.supported-apps li {
  color: #666;
  margin-bottom: 0.5rem;
}

.download-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
}

.generic-document-viewer {
  width: 100%;
  height: 100%;
  position: relative;
}

.fallback-options {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 3rem;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  text-align: center;
  z-index: 10;
}

.fallback-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.fallback-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-top: 2rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.2s ease;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
  transform: translateY(-1px);
}

.btn-large {
  padding: 1rem 2rem;
  font-size: 1rem;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .player-content {
    padding: 1rem;
  }
  
  .office-info {
    padding: 2rem;
    margin: 1rem;
  }
  
  .download-actions {
    flex-direction: column;
  }
}
</style>



